import axios from 'axios'
import store from '@/store'
import { getToken } from '@/utils/auth'
import { baseURL } from '@/utils/changeUrl'
import Cookies from 'js-cookie' 
import { Notification } from 'element-ui'

// create an axios instance
const service = axios.create({ 
  // baseURL: process.env.VUE_APP_BASE_API, //记得打开
  baseURL: baseURL,   //测试环境
  // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 15000 // request timeout
})
function getUrlKey(name) {
  return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ""])[1].replace(/\+/g, '%20')) || null
}
// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    // if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      let pageToken = getToken() ||getUrlKey('token')
      config.headers['Authorization'] = pageToken  // 记得放开
      // config.headers['Authorization'] = 'eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6IjgyOGZhMzAyLWRmODQtNDMwNy04MDRhLWE0ZTUxOTdiOWUzNyJ9.8nw0cLDpPbEvQqhtwOLOa9AOxD3Aq_1zVr3YJIqHY4EqUcGbkH1kFXiLjPxOeqIFUcAP2-GwJc1NltNmFQ6QtA'
      // config.headers['Authorization'] = 'eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6IjkyZjNjZWZkLWM5MTYtNGJiYS05MzcxLTgyNWM4NmI1YjA5MiJ9.KNeWwp4Re62oYWkGHFMh27dGjtQsscdb-D5qUhC7g-s4y4Q9P_rnUdgY-66xex8DywHas4XoKjFNrmmz-Ow_dw'
      // console.log('wwww',getToken());
    // }
    // config.headers['Authorization'] = 'eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6ImJhMjAxZGQyLWUyMDItNGU4OC04NjRhLTkzNDAwNjlkOGM1YSJ9.j9212jDLoBTzdxrl_BywBVnXgAAuh_kikim7eTDBFGfCdrHTpIk4ymvQxq_rj68FMBmpFzXW_0PFJPYp9h_GoA'
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const code = response.status
    if (code < 200 || code > 300) {
      Notification.error({
        title: response.message
      })
      return Promise.reject('error')
    } else {
      return response.data
    }
  },
  error => {
    let code = 0
    try {
      code = error.response.data.status
    } catch (e) {
      if (error.toString().indexOf('Error: timeout') !== -1) {
        Notification.error({
          title: '网络请求超时',
          duration: 5000
        })
        return Promise.reject(error)
      }
    }
    if (code) {
      if (code === 401) {
        store.dispatch('user/logout').then(() => {
          // 用户登录界面提示
          Cookies.set('point', 401)
          location.reload()
        })
      } else {
        const errorMsg = error.response.data.message
        if (errorMsg !== undefined) {
          Notification.error({
            title: errorMsg,
            duration: 5000
          })
        }
      }
    } else {
      Notification.error({
        title: '接口请求失败',
        duration: 5000
      })
    }
    return Promise.reject(error)
  }
)

export default service
